package graphIndexerPackage;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import mapPackage.IRoute;
import mapPackage.IVille;
import mapPackage.RouteIterator;
import mapPackage.VilleIterator;

public class ZipReader {
	ZipFile zipFile;
	
	int nbVilles = 0;
	int nbRoutes = 0;
	
	public ZipReader( String filename ) {
		try {
			zipFile = new ZipFile(filename);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
		try {
			zipFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void loadZip( Map<String, IRoute> hashRoutes, Map<String, IVille> hashVilles, int cacheRoute, int cacheVille ) {
		int cr = 0, cv = 0;
		for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); ) {
			ZipEntry z = e.nextElement();
			String entryName = z.getName();
			if ( entryName.startsWith("R_" )) {
				if ( cr <= cacheRoute ) {
					hashRoutes.put(entryName.substring(2), null);
				}
				++cr;
			} else {
				if ( entryName.startsWith("V_") ) {
					if ( cv <= cacheVille ) {
						hashVilles.put(entryName.substring(2), null);
					}
					++cv;
				}
			}
		}
		nbVilles = cv;
		nbRoutes = cr;
	}
	
	public InputStream getVilleInputStream( String ville ) {
		ZipEntry zipEntry = zipFile.getEntry("V_"+ville);
		try {
			return zipFile.getInputStream(zipEntry);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public InputStream getRouteInputStream( String route ) {
		ZipEntry zipEntry = zipFile.getEntry("R_"+route);
		try {
			return zipFile.getInputStream(zipEntry);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public long getChecksum() {
		long checksum = 0;
		ZipEntry zipEntry = zipFile.getEntry("ADLER32");
		if ( zipEntry != null ) {
			try {
				byte[] buffer = new byte[50];
				InputStream zipInput = (zipFile.getInputStream(zipEntry));
				if ( zipInput != null ) {
					int len = zipInput.read(buffer);
					String str = new String(buffer, 0, len);
					checksum = Long.parseLong(str);
				}
			} catch (IOException e ) {
				e.printStackTrace();
			}
		}
		return checksum;
	}

	public Iterator<String> getVilleIterator(String strStartFilter) {
		return new VilleIterator(zipFile.entries(), strStartFilter);
	}
	
	public Iterator<String> getRouteIterator(String strStartFilter) {
		return new RouteIterator(zipFile.entries(), strStartFilter);
	}
	
	public int getNbVilles() {
		return nbVilles;
	}
	
	public int getNbRoutes() {
		return nbRoutes;
	}
}
